package com.sanchunhui.psc.bluetooth.bt

import android.bluetooth.BluetoothDevice
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.eightbitlab.rxbus.Bus
import com.sanchunhui.psc.R
import com.sanchunhui.psc.event.BlueClickConnectEvent
import org.jetbrains.anko.find

/**
 * @Author zyx
 * @Date 2021/6/4-10:20
 * @Dscribe
 */
class BtDeviceListAdapter(val context: AppCompatActivity) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var blueBeans: MutableList<BluetoothDevice> = mutableListOf()

    fun setData(datas: MutableList<BluetoothDevice>) {
        this.blueBeans = datas
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.recy_blue_item_layout, parent, false)
        return  BlueListViewHolder(view)
    }

    override fun getItemCount(): Int = blueBeans.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as BlueListViewHolder).bindData(blueBeans[position])
    }

    inner class  BlueListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val addressTv : TextView
        val nameTv : TextView
        val statusTv : TextView

        lateinit var bluetoothDeviceBean: BluetoothDevice

        init {

            addressTv = itemView.find(R.id.blue_item_addr_tv)
            nameTv = itemView.find(R.id.blue_item_name_tv)
            statusTv = itemView.find(R.id.blue_item_status_tv)

            itemView.setOnClickListener {
                val dev: BluetoothDevice = bluetoothDeviceBean
                Toast.makeText(context, "开始连接...", Toast.LENGTH_SHORT).show()
                Bus.send(BlueClickConnectEvent(dev))
            }

            //todo 解绑估计需要系统 api，后面看看源码是怎么实现的

        }

        fun bindData(bluetoothDevice: BluetoothDevice) {
            this.bluetoothDeviceBean = bluetoothDevice
            addressTv.text = bluetoothDeviceBean.address
            nameTv.text = bluetoothDeviceBean.name

            if (bluetoothDeviceBean.bondState == BluetoothDevice.BOND_BONDED) {
                statusTv.text = "(已配对)"
                statusTv.setTextColor(Color.parseColor("#ff009688"))
            } else {
                statusTv.text = "(未配对)"
                statusTv.setTextColor(Color.parseColor("#ffFF5722"))

            }

        }
    }
}